using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace IQIGame.Onigao.Game
{
    public class UIAssetHelper
    {
        private ResLoader _resLoader;

        private Dictionary<int, string> dicUGobjID2AssetPath = new(8);


        public UIAssetHelper(ResLoader resLoader)
        {
            this._resLoader = resLoader;
        }

        private void RecordIdAssetPath(int instanceId, string path)
        {
            this.dicUGobjID2AssetPath[instanceId] = path;
        }

        private bool IsCurrAssetPath(int instanceId, string path)
        {
            return dicUGobjID2AssetPath.TryGetValue(instanceId, out var oldPath) ? string.Equals(oldPath, path) : false;
        }


        public void SetImageSprite(Image img, string assetPath)
        {
            this.SetImageSpriteAsync(img, assetPath).Forget();
        }

        private async UniTaskVoid SetImageSpriteAsync(Image img, string assetPath)
        {
            if (string.IsNullOrEmpty(assetPath))
            {
                LogGame.LogError("SetImageSpriteAsync assetPath is NullOrEmpty");
                return;
            }
            this.RecordIdAssetPath(img.GetInstanceID(), assetPath);
            var sprite = await _resLoader.LoadABAssetAwait<Sprite>(assetPath);
            if (this.IsCurrAssetPath(img.GetInstanceID(), assetPath))
                img.sprite = sprite;
        }

        public void SetRawImageTexture(RawImage img, string assetPath)
        {
            this.SetRawImageTextureAsync(img, assetPath).Forget();
        }

        private async UniTaskVoid SetRawImageTextureAsync(RawImage img, string assetPath)
        {
            if (string.IsNullOrEmpty(assetPath))
            {
                LogGame.LogError("SetImageSpriteAsync assetPath is NullOrEmpty");
                return;
            }

            this.RecordIdAssetPath(img.GetInstanceID(), assetPath);
            var texture = await _resLoader.LoadABAssetAwait<Texture2D>(assetPath);
            if (this.IsCurrAssetPath(img.GetInstanceID(), assetPath))
                img.texture = texture;
        }

        public void Clear()
        {
            this.ClearRecord();
            _resLoader = null;
        }

        private void ClearRecord()
        {
            this.dicUGobjID2AssetPath.Clear();
        }
    }
}
